﻿using Markdig;
using Microsoft.Web.WebView2.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LPBToolsNF
{
    public class WebView2EnvironmentManager
    {
        private static readonly Lazy<WebView2EnvironmentManager> lazy =
        new Lazy<WebView2EnvironmentManager>(() => new WebView2EnvironmentManager());

        public static WebView2EnvironmentManager Instance => lazy.Value;

        public CoreWebView2Environment Environment { get; private set; }
        public bool IsInitialized { get; private set; }

        private WebView2EnvironmentManager() { }

        public async Task InitializeAsync()
        {
            if (IsInitialized)
                return;

            try
            {
                string userDataFolder = Path.Combine(
                    System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData),
                    "LBStudio",
                    "WebView2");
                // 确保WebView2已初始化
                // 创建环境选项
                var options = new CoreWebView2EnvironmentOptions();                
                // 初始化环境（仅一次）
                Environment = await CoreWebView2Environment.CreateAsync(null, userDataFolder, options);
                IsInitialized = true;
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"WebView2 环境初始化失败：\r\n{ex.Message}", ex);
            }
        }
    }
}
